//
//  UIDynamicAnimator+UIDynamicAnimatorWithBlock.m
//  etionUI
//
//  Created by wjxfhxy on 14-4-1.
//  Copyright (c) 2014年 GuangZhouXuanWu. All rights reserved.
//

#import "UIDynamicAnimatorWithBlock.h"

@interface UIDynamicAnimatorWithBlock ()<UIDynamicAnimatorDelegate>
{
    void(^willResumeBlock)();
    void(^didPauseBlock)();
    
    UIDynamicAnimator *_anomator;
}

@end

@implementation UIDynamicAnimatorWithBlock

-(id)initWithReferenceView:(UIView*)referenceView dynamicBehaviors:(NSArray*)arBehavior willResumBlock:(void(^)())resumeBlock didPauseBlock:(void(^)())pauseBlock
{
    if(arBehavior.count<=0)
        return nil;
    
    self = [super init];
    
    _anomator = [[UIDynamicAnimator alloc]initWithReferenceView:referenceView];
    _anomator.delegate = self;
    for(UIDynamicBehavior *behavior in arBehavior)
        [_anomator addBehavior:behavior];
    
    willResumeBlock = Block_copy(resumeBlock);
    didPauseBlock = Block_copy(pauseBlock);
    
    return self;
}

-(void)dealloc
{
    if(willResumeBlock != NULL)
        Block_release(willResumeBlock);
    if(didPauseBlock != NULL)
        Block_release(didPauseBlock);
    
    [_anomator release_mm];
    
    superdealloc_mm;
}

-(void)dynamicAnimatorWillResume:(UIDynamicAnimator *)animator
{
    if(willResumeBlock != NULL)
        willResumeBlock();
}

-(void)dynamicAnimatorDidPause:(UIDynamicAnimator *)animator
{
    if(didPauseBlock != NULL)
        didPauseBlock();
}

+(void)animatorWithReferenceView:(UIView*)referenceView dynamicBehaviors:(NSArray *)arBehavior willResumBlock:(void (^)())resumeBlock didPauseBlock:(void (^)())pauseBlock
{
    UIDynamicAnimatorWithBlock *block = [[[UIDynamicAnimatorWithBlock alloc]initWithReferenceView:referenceView dynamicBehaviors:arBehavior willResumBlock:^
    {
        if(resumeBlock != NULL)
            resumeBlock();
    } didPauseBlock:^
    {
        if(pauseBlock != NULL)
            pauseBlock();
        [referenceView setAssociatedRetainNonatomicValue:nil withKey:"UIDynamicAnimatorWithBlock"];
    }] autorelease_mm];
    [referenceView setAssociatedRetainNonatomicValue:block withKey:"UIDynamicAnimatorWithBlock"];
}

+(void)animatorWithReferenceView:(UIView *)referenceView dynamicBehaviors:(NSArray *)arBehavior didPauseBlock:(void (^)())pauseBlock
{
    [UIDynamicAnimatorWithBlock animatorWithReferenceView:referenceView dynamicBehaviors:arBehavior willResumBlock:^
    {
        
    } didPauseBlock:pauseBlock];
}

+(void)animatorWithReferenceView:(UIView *)referenceView dynamicBehaviors:(NSArray *)arBehavior
{
    [UIDynamicAnimatorWithBlock animatorWithReferenceView:referenceView dynamicBehaviors:arBehavior willResumBlock:^
    {
    } didPauseBlock:^
    {
    }];
}

@end
